package com.a2v2.online.store.common.aop;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import com.a2v2.online.store.common.exception.DatabaseAccessException;
import com.a2v2.online.store.common.logger.contract.ILogger;
import com.a2v2.online.store.service.constant.ErrorCode;
import com.a2v2.online.store.service.exception.ServiceException;
@Aspect
public class ExceptionHandlerAspect {
	@Autowired
	ILogger logger;
	/**
	 *
	 * @param pEx runtime exception param.
	 */
	@Order(value=1) 
	@AfterThrowing(throwing = "pEx", value = "com.expresspay.common.aop.SystemPointcut.inDataAccessLayer()")
	public final void doDAOExceptionHandling(final Throwable pEx) {
		String aMessage = pEx.getMessage();
		if (pEx.getCause() != null) {
			aMessage += " :: Root Cause :: " + pEx.getCause().getMessage();
		}
		logger.logError(this.getClass(), "DB-001 DATABASE EXCEPTION !!!!!!!!!!!!!!!!Message::"+aMessage, pEx);
		throw new DatabaseAccessException(ErrorCode.SYSTEM002, pEx);
	}
	@Order(value=2)
	@AfterThrowing(throwing = "pEx", value = "com.expresspay.common.aop.SystemPointcut.inServiceLayer()")
	public final void doServiceExcpetionHandling(final RuntimeException pEx) throws Exception{
		logger.logError(this.getClass(), "SE-001 SERVICE EXCEPTION !!!!!!!!!!!!!!!!Message::"+ pEx.getMessage(), pEx);
		if (pEx instanceof ServiceException) {
        	throw pEx;
        }
        else {
        	throw new ServiceException(ErrorCode.SYSTEM001);
        }

	}

}
